<?php

//require_once 'functions.php';

/*if(!isset($showcomments))
{
    $showcomments = true;
    if(arr::get($_REQUEST, 'comments') == 'hide')
    {
        $showcomments = false;
    }
}*/

/*if(!isset($invoice_id))
{
    $invoice_id = intval($_REQUEST['invoice_id']);
}

$seperate = 'no';
if(arr::get($_REQUEST, 'seperate') == 'yes')
{
    $seperate = 'yes';
}

*/



// Get any account_ids of sub accounts if there are any
$subAccounts = array();
$checkIds = array();
$checkIds[] = $account_id;
while(count($checkIds) > 0)
{
    $tAccId = array_pop($checkIds);
    $subAccounts[] = $tAccId;
    $q = "SELECT * FROM account WHERE parent_id='$tAccId'";
    $res = $db->query(Database::SELECT, $q);
    foreach($res as $row)
    {
        array_push($checkIds, $row['account_id']);
    }
}

$multiInvoices = (count($invoices) > 1);

ob_start();
?>
<style type="text/css" media="print">
.buttonDiv{
    display: none;
}
</style>
<style type="text/css" media="screen">
.buttonDiv{
    border: 1px solid #7b7b7b;
    width: 800px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #b8b8b8;
    color: #575757;
}
</style>
<center>
    <?php
    if(!isset($print_pdf) && !isset($print_popup))
    {
        ?>
        <div class="buttonDiv">
            <form>

                <script language="Javascript">
                    function popupPrint(){
                        var myWidth = 0;
                        var myHeight = 0;
                        var popupWidth = 600;
                        var popupHeight = 500;
                        var screenW = 0;
                        var screenH = 0;
                        if(document.all){
                            screenW = document.body.clientWidth;
                            screenH = document.body.clientHeight;
                        }else{
                            screenW = window.screen.width;
                            screenH = window.screen.height;
                        }
                        if(screenW == 0){
                            screenW = popupWidth;
                            screenH = popupHeight;
                        }

                        myWidth = (screenW/2) - ((popupWidth/2) + 10);
                        myHeight = (screenH/2) - ((popupHeight/2) + 50);

                        // Check for displaying comments
                        var comments = '&comments=hide';
                        if(document.getElementById('showCommentsOnInvoiceChk') && document.getElementById('showCommentsOnInvoiceChk').checked){
                            comments = '';
                        }
                        var win2 = window.open("printinvoice.php?account_id=<?php echo $account_id ?>&invoice_id=<?php echo $invoice_id ?>"+comments,"PrintWindow","status=no,height="+popupHeight+",width="+popupWidth+",resizable=yes,left=" + myWidth + ",top=" + myHeight + ",screenX=" + myWidth + ",screenY=" + myHeight + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
                        //win2.focus();
                    }
                    function checkComments(){
                        var comments = '&comments=hide';
                        if(document.getElementById('showCommentsOnInvoiceChk') && document.getElementById('showCommentsOnInvoiceChk').checked){
                            comments = '';
                        }
                        return comments;
                    }
                </script>
                <?php if( ! $customer): ?>
                <input type="button" value="Edit Invoice" onclick="openPage('center','editInvoicePage-<?php echo $invoice_id ?>','editinvoice.php?invoice_id=<?php echo $invoice_id ?>','Edit Invoice #<?php echo $invoice_id ?>','Edit Invoice #<?php echo $invoice_id ?>');" />
                <?php endif; ?><input type="button" value="Download PDF" onclick="document.location='pdfinvoice.php?account_id=<?php echo $account_id ?>&invoice_id=<?php echo $invoice_id ?>'+checkComments();" />
                <input type="button" value="Print" onclick="popupPrint();" />
                <?php if( ! $customer): ?><label><input type="checkbox" id="showCommentsOnInvoiceChk" /> Show Comments</label><?php endif; ?> <br />
            </form>
        </div>
        <?php
    }
    ?>
    <table width="800" cellpading="2" cellspacing="0" border="0">
        <tr>
            <td>
                <table width="800" cellpadding="2" cellspacing="0" border="0">
                    <tr>
                        <?php
                        $logoURL = $dot.'rwastelogo.jpg';
                        if(isset($print_pdf))
                        {
                            $logoURL = dirname(__FILE__).'/'.$logoURL;
                        }
                        ?>
                        <td valign="top"><img src="<?php echo $logoURL ?>" border="0"></td>

                        <td valign="top" align="right">
                            <br>

                            <table width="300" cellpaddng="2" cellspacing="0" style="border: 1px solid #cccccc;">
                                <tr>
                                    <td bgcolor="#CCCCCC" valign="top">
                                <center>
                                    <font face="arial" size="2"><b>Invoice #<?php echo $invoice_num_display ?></b></font>
                                </center>
                                </td>
                                </tr>

                                <tr>
                                    <td height="50"  bgcolor="#F0F0F0" align="left">
                                <center>
                                    <table cellpadding="2" cellspacing="3" border="0">
                                        <tr><td align="left">
                                                <font face="arial" size="2"><b>Date Created:</b> </font>
                                            </td>
                                            <td	align="left">
                                                <font face="arial" size="2"><?php echo date("F j, Y", strtotime($invoiceData['invoice_datestart'])) ?></font>
                                        </tr>
                                        <?php if($invoiceData['invoice_servicestart'] != '0000-00-00' && $invoiceData['invoice_serviceend'] != '0000-00-00'): ?>
                                            <tr><td align="left">
                                                    <font face="arial" size="2"><b>Service Period:</b> </font>
                                                </td>
                                                <td  align="left">
                                                    <font face="arial" size="2"><?php echo date("m/d/Y", strtotime($invoiceData['invoice_servicestart'])) ?> - <?php echo date("m/d/Y", strtotime($invoiceData['invoice_serviceend'])) ?></font>
                                            </tr>
                                        <?php endif; ?>
                                        <tr style="color: #dc0000;"><td align="left">
                                                <font face="arial" size="2" color="#dc0000"><b>Date Due:</b></font>
                                            </td>
                                            <td align="left">
                                                <font face="arial" size="2" color="#dc0000"><?php echo date("F j, Y", strtotime($invoiceData['invoice_datestart']) + ($accountData['billing_payment_term'] * 86400)) ?></font>
                                            </td>
                                        </tr>
                                    </table>
                                </center>
                                </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table><br>
    <br>
    <hr width="800" size="1" color="#CCCCCC">
    <br>

    <table width="800" cellpadding="2" cellspacing="0" border="0">
        <tr>
            <td align="left" valign="top" width="400"><font face="arial" size="2"><b>Customer Information:</b><br>
                <font face="arial" size="4"><b><?php echo strtoupper($accountData['account_name']) ?></b></font><br>
                <font face="arial" size="2"><?php echo strtoupper(str_replace("\n", "<br />", $accountData['billing_address'])) ?><br>
                <?php echo strtoupper($accountData['billing_city']) ?>, <?php echo strtoupper($accountData['billing_state']) ?> <?php echo strtoupper($accountData['billing_zip']) ?><br>
                </font></font></td>

                <td valign="top" align="right" width="400">
                    <font face="arial" size="2"><b>Service Address:</b><br>
                    <font face="arial" size="2"><?php echo strtoupper($accountData['service_address']) ?></font><br>
                    <?php echo $accountData['service_city'] ? strtoupper($accountData['service_city']).',' : '' ?> <?php echo strtoupper($accountData['service_state']) ?> <?php echo strtoupper($accountData['service_zip']) ?><br>
                    </font>
                    </td>
                    </tr>
                    </table><br>
                    <hr width="800" size="1" color="#CCCCCC">
                    <br>
                    <br>






                    <!-- New stuff 10/10/2010 -->

                    <b><font face="arial" size="4">A Summary of Your Bill For All Accounts Below</font></b><br><br>

                    <hr width="800" size="1" color="#CCCCCC">
                    %%%content_totals%%%

                    <table width="800" cellpadding="10" cellspacing="0" style="border: 1px solid #cccccc;">
                        <tr>
                            <td width="800" bgcolor="#DEDEDE" valign="top"><center><font face="arial" size="2"><b>Detailed Information For All Accounts Combined </b></font><br><font face="VERDANA" size="1"><A HREF="#">View Recycling Detail</A> | <A HREF="#">View Recycling Stats</A> | <A HREF="#">View Tonage Stats</A>&nbsp;&nbsp;&nbsp;&nbsp;</center></td></tr></table>



                            <hr width="800" size="1" color="#CCCCCC">

                            %%%content_savings%%%

                            <!-- PAGE BREAK -->
                            <center>
                                <b><font face="arial" size="4">Your Bill In Full Detail For All Accounts</font></b><br>
                                <br>
                                <hr width="800" size="1" color="#CCCCCC">
                                </center>
                                <br>












                                <?php
                                // Begin multi invoice loop
                                $runningBenchmark = 0;
                                $runningNew = 0;
                                $runningHauler = 0;
                                $rubiconFee = 0;
                                $totalCreditAmount = 0;
                                $q = "SELECT * FROM invoice_row, service WHERE serv_group=serv_group_id AND invoice_id IN('".implode("','", $invoices)."') AND serv_deleted = 'no'";
                                $q .= " GROUP BY serv_recur, serv_group ORDER BY serv_dateadded DESC";
                                $res = $db->query(Database::SELECT, $q);
                                $services = array();
                                foreach($res as $row)
                                {
                                    if(!isset($services[$row['invoice_id']]))
                                    {
                                        $services[$row['invoice_id']] = array(
                                            'perminate' => array(),
                                            'ondemand' => array(),
                                            'item' => array(),
                                        );
                                    }
                                    $services[$row['invoice_id']][$row['serv_recur']][] = $row;
                                }
                                foreach($invoices as $invoice_id):
                                    $myRows = $services[$invoice_id]['perminate'];
                                    if(count($myRows) > 0):
                                        ?>
                                        <table width="800" cellpadding="2" cellspacing="0" style="border: 1px solid #cccccc;">
                                            <tr>
                                                <td align="left" width="700" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Permanent Service</b>
                                                    <?php
                                                    if($multiInvoices):
                                                        // Display accountname - sericeaddress - servicecity - servicestate - serviceszip
                                                        $aid = $myRows[0]['account_id'];
                                                        $q = "SELECT * FROM account WHERE account_id='$aid'";
                                                        $subAccData = $db->query(Database::SELECT, $q)->current();
                                                        echo("&nbsp;&nbsp;&nbsp;&nbsp;");
                                                        echo('<font face="arial" size="1">');
                                                        echo('Acc. #'.$subAccData['account_id'].' - ');
                                                        //if(trim($subAccData['store_number']) != ''){
                                                        //  echo($subAccData['store_number'].' - ');
                                                        //}
                                                        echo($subAccData['account_name'].' - '.$subAccData['service_address'].' - '.$subAccData['service_city'].' - '.$subAccData['service_state'].' - '.$subAccData['service_zip']);
                                                        echo('</font>');
                                                    endif;
                                                    ?>
                                                    </font></td>
                                                <td align="left" width="100" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Amount</b></font></td>

                                            </tr>
                                        </table>

                                        <?php
                                    endif;
                                    foreach($myRows as $row):
                                        //$costs = getServiceCosts($row['serv_group']);
                                        //$runningBenchmark += $costs['benchmark'];
                                        //$runningNew += $costs['newprice'];
                                        $runningBenchmark += $row['row_benchmark'];
                                        $runningNew += $row['row_newprice'];
                                        $runningHauler += $row['row_hauler_cost'];
                                        $dateOrdered = "";
                                        if($row['row_dateordered'] != "0000-00-00 00:00:00"):
                                            $dateOrdered = date("m/d/Y", strtotime($row['row_dateordered']));
                                        endif;
                                        $haul_cost = $accountData['invoice_format'] == 'split' ? $row['row_hauler_cost'] : $row['row_newprice'];
                                        $rubiconFee += $row['row_newprice'] - $row['row_hauler_cost'];
                                        ?>
                                        <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                            <tr>
                                                <td align="left" width="700" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $row['row_servicename'] ?></font></td>
                                                <td align="left" width="100" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($haul_cost - $row['row_fuel_fee'] - $row['row_adminfee'] - $row['row_franchise'] - $row['row_latefee'], 2) ?></font></td>

                                            </tr>
                                            <?php
                                            if($accountData['invoice_format'] == 'split' AND $row['row_newprice'] - $row['row_hauler_cost'] != 0):
                                                ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Rubicon Management Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_newprice'] - $row['row_hauler_cost'], 2) ?></font></td>
                                                </tr>
                                                <?php
                                            endif;
                                            if($row['row_fuel_fee'] != 0):
                                                ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Fuel/Environmental Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_fuel_fee'], 2) ?></font></td>
                                                </tr>
                                            <?php endif;
                                            if($row['row_adminfee'] != 0): ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Admin Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_adminfee'], 2) ?></font></td>
                                                </tr>
                                            <?php endif;
                                            if($row['row_franchise'] != 0): ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Franchise Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_franchise'], 2) ?></font></td>
                                                </tr>
                                            <?php endif;
                                            if($row['row_latefee'] != 0): ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Late Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_latefee'], 2) ?></font></td>
                                                </tr>
                                            <?php endif; ?>

                                        </table>
                                        <hr width="800" size="1" color="#CCCCCC">
                                        <?php
                                    endforeach;
                                    //if(count($myRows) > 0){
                                    if(false):
                                        ?>
                                        <hr width="800" size="1" color="#CCCCCC">
                                        <?php
                                    endif;

                                    $myRows = $services[$invoice_id]['ondemand'];
                                    $hr = FALSE;
                                    if(count($myRows) > 0):
                                        $hr = TRUE;
                                        ?>
                                        <table width="800" cellpadding="2" cellspacing="0" style="border: 1px solid #cccccc;">
                                            <tr>
                                                <td align="left" width="90" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Date Ordered</b></font></td>
                                                <td align="left" width="370" bgcolor="#DEDEDE" valign="top0"><font face="arial" size="2"><b>On Call Service</b></font></td>
                                                <td align="left" width="80" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Per ton</b></font></td>
                                                <td align="left" width="80" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Tonnage</b></font></td>
                                                <td align="left" width="80" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Haul</b></font></td>
                                                <td align="left" width="100" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Amount</b></font></td>
                                            </tr>
                                        </table>
                                        <?php
                                    endif;
                                    foreach($myRows as $row):
                                        $costs = getServiceCosts($row['serv_group'], $accountData['rubicon_fee_percent']);
                                        //$runningBenchmark	+= $costs['benchmark'];
                                        //$runningNew += $costs['newprice'];
                                        $runningBenchmark += $row['row_benchmark'];
                                        $runningNew += $row['row_newprice'];
                                        $runningHauler += $row['row_hauler_cost'];
                                        $dateOrdered = "";
                                        if($row['row_dateordered'] != "0000-00-00 00:00:00"):
                                            $dateOrdered = date("m/d/Y", strtotime($row['row_dateordered']));
                                        endif;
                                        $name = $row['row_servicename'];
                                        $perton = floatval($row['row_perton']);
                                        $tonnage = floatval($row['row_tons']);
                                        $haul_cost = $accountData['invoice_format'] == 'split' ? $row['row_hauler_cost'] : $row['row_newprice'];
                                        $rubiconFee += $row['row_newprice'] - $row['row_hauler_cost'];
                                        ?>
                                        <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                            <tr>
                                                <td align="left" width="90" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $dateOrdered ?></font></td>
                                                <td align="left" width="370" bgcolor="#F0F0F0" valign="top0"><font face="arial" size="2"><?php echo $name ?></font></td>
                                                <td align="left" width="80" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($perton, 2) ?></font></td>
                                                <td align="left" width="80" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo number_format($tonnage, 2) ?></font></td>
                                                <td align="left" width="80" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_haul_cost'], 2) ?></font></td>
                                                <td align="left" width="100" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($haul_cost - $row['row_fuel_fee'] - $row['row_adminfee'] - $row['row_franchise'] - $row['row_latefee'], 2) ?></font></td>
                                            </tr>
                                            <?php
                                            if($accountData['invoice_format'] == 'split' AND $row['row_newprice'] - $row['row_hauler_cost'] != 0):
                                                ?>
                                                <tr><td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $dateOrdered ?></font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Rubicon Management Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_newprice'] - $row['row_hauler_cost'], 2) ?></font></td>
                                                </tr>
                                                <?php
                                            endif;
                                            if($row['row_fuel_fee'] != 0):
                                                ?>
                                                <tr><td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $dateOrdered ?></font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Fuel/Environmental Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_fuel_fee'], 2) ?></font></td>
                                                </tr>
                                                <?php
                                            endif;
                                            if($row['row_adminfee'] != 0):
                                                ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $dateOrdered ?></font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Admin Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_adminfee'], 2) ?></font></td>
                                                </tr>
                                            <?php endif;
                                            if($row['row_franchise'] != 0): ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $dateOrdered ?></font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Franchise Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_franchise'], 2) ?></font></td>
                                                </tr>
                                            <?php endif;
                                            if($row['row_latefee'] != 0): ?>
                                                <tr>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $dateOrdered ?></font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">Late Fee</font></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"></td>
                                                    <td align="left" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_latefee'], 2) ?></font></td>
                                                </tr>
                                            <?php endif; ?>

                                        </table>


                                        <?php
                                    endforeach;

                                    $myRows = $services[$invoice_id]['item'];
                                    if(count($myRows) > 0):
                                        $hr = TRUE;
                                        ?>
                                        <table width="800" cellpadding="2" cellspacing="0" style="border: 1px solid #cccccc;">
                                            <tr>
                                                <td align="left" width="110" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Date</b></font></td>
                                                <td align="left" width="390" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Service</b></font></td>
                                                <td align="left" width="100" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Unit Price</b></font></td>
                                                <td align="left" width="100" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Quantity</b></font></td>
                                                <td align="left" width="100" bgcolor="#DEDEDE" valign="top"><font face="arial" size="2"><b>Total</b></font></td>
                                            </tr>
                                        </table>
                                        <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                            <?php
                                            foreach($myRows as $row):
                                                $date = '<em>None</em>';
                                                if($row['row_dateordered'] != '0000-00-00 00:00:00'):
                                                    $date = date("m/d/Y", strtotime($row['row_dateordered']));
                                                endif;
                                                $runningBenchmark += $row['row_item_price'] * $row['row_item_qty'];
                                                $runningNew += $row['row_item_price'] * $row['row_item_qty'];
                                                $runningHauler += $row['row_item_price'] * $row['row_item_qty'];
                                                ?>
                                                <tr>
                                                    <td align="left" width="110" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $date ?></font></td>
                                                    <td align="left" width="390" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $row['row_servicename'] ?></font></td>
                                                    <td align="left" width="100" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_item_price'], 2) ?></font></td>
                                                    <td align="left" width="100" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo number_format($row['row_item_qty'], 0) ?> <?php echo $row['row_item_unit'] ?></font></td>
                                                    <td align="left" width="100" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2">$<?php echo number_format($row['row_item_price'] * $row['row_item_qty'], 2) ?></font></td>
                                                </tr>
                                                <?php
                                            endforeach;
                                            ?>
                                        </table>
                                        <?php
                                    endif; // End itemized loop


                                    $q = "SELECT * FROM credit WHERE invoice_id=$invoice_id";// AND account_id=$account_id"; This messed up creation of master invoices
                                    $res = $db->query(Database::SELECT, $q);
                                    foreach($res as $row):
                                        $displayDate = date("m/d/Y", strtotime($row['credit_date']));
                                        $name = $row['credit_desc'];
                                        $neg = '';
                                        if($row['credit_type'] == 'credit'):
                                            $neg = '-';
                                            $name = "Credit: $name";
                                            $totalCreditAmount -= $row['credit_amount'];
                                        elseif($row['credit_type'] == 'fee'):
                                            $totalCreditAmount += $row['credit_amount'];
                                        elseif($row['credit_type'] == 'rubiconfee'):
                                            //$totalCreditAmount += $row['credit_amount'];
                                            $runningNew += $row['credit_amount'];
                                            $rubiconFee += $row['credit_amount'];
                                        else:
                                            $name = "Debit: $name";
                                            $totalCreditAmount += $row['credit_amount'];
                                        endif;
                                        $amount = $neg.'$'.number_format($row['credit_amount'], 2);
                                        ?>
                                        <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                            <tr><td align="left" width="90" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $displayDate ?></font></td>
                                                <td align="left" width="370" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $name ?></font></td>
                                                <td align="left" width="80" bgcolor="#F0F0F0" valign="top"></td>
                                                <td align="left" width="80" bgcolor="#F0F0F0" valign="top"></td>
                                                <td align="left" width="80" bgcolor="#F0F0F0" valign="top"></td>
                                                <td align="left" width="100" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><?php echo $amount ?></font></td>
                                            </tr>
                                        </table>
                                        <?php
                                    endforeach;
                                    if($hr):
                                        ?>
                                        <hr width="800" size="1" color="#CCCCCC">
                                        <?php
                                    endif;
                                endforeach; // End multi invoice loop

                                //$rubiconFee = $runningNew - $runningHauler; //$runningBenchmark-$runningNew;

                                $hauler_pricing = $accountData['invoice_format'] == 'split' ? $runningNew - $rubiconFee : $runningNew;

                                ob_start();
                                ?>

                                <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                    <tr>
                                        <td width="100" bgcolor="#F0F0F0" valign="top">&nbsp;</td>

                                        <td width="400" bgcolor="#F0F0F0" valign="top0">&nbsp;</td>

                                        <td align="left" width="200" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><b>Your Price Would Have Been</b></font></td>

                                        <td align="left" width="100" valign="top"><font face="arial" size="2">$<?php echo number_format($runningBenchmark, 2) ?></font></td>
                                    </tr>
                                </table>
                                <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                    <tr>
                                        <td width="100" bgcolor="#F0F0F0" valign="top">&nbsp;</td>

                                        <td width="400" bgcolor="#F0F0F0" valign="top0">&nbsp;</td>

                                        <td align="left" width="200" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><b>Rubicon Hauler Pricing</b></font></td>

                                        <td align="left" width="100" valign="top"><font face="arial" size="2">$<?php echo number_format($hauler_pricing, 2) ?></font></td>
                                    </tr>
                                </table>
                                <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                    <tr>
                                        <td width="100" bgcolor="#F0F0F0" valign="top">&nbsp;</td>

                                        <td width="400" bgcolor="#F0F0F0" valign="top0">&nbsp;</td>

                                        <td align="left" width="200" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><b>Total Hauler Savings</b></font></td>

                                        <td align="left" width="100" valign="top"><font face="arial" size="2">$<?php echo number_format($runningBenchmark - $hauler_pricing, 2) ?></font></td>
                                    </tr>
                                </table>

                                <?php if($rubiconFee != 0 AND $accountData['invoice_format'] == 'split'): ?>
                                    <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                        <tr>
                                            <td width="100" bgcolor="#F0F0F0" valign="top">&nbsp;</td>

                                            <td width="400" bgcolor="#F0F0F0" valign="top0">&nbsp;</td>

                                            <td align="left" width="200" bgcolor="#F0F0F0" valign="top"><font face="arial" size="2"><b>Rubicon Management Fee</b></font></td>

                                            <td align="left" width="100" valign="top"><font face="arial" size="2">$<?php echo number_format($rubiconFee, 2) ?></font></td>
                                        </tr>
                                    </table>
                                <?php endif; ?>

                                <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                    <tr>
                                        <td width="100" bgcolor="#F0F0F0" valign="top">&nbsp;</td>

                                        <td width="400" bgcolor="#F0F0F0" valign="top">&nbsp;</td>

                                        <td align="left" width="200" bgcolor="#F0F0F0" valign="top"><font face="arial" size="4"><b>Pay this amount</b></font></td>

                                        <td align="left" width="100" valign="top"><font face="arial" size="4"><b>$<?php echo number_format($runningNew + $totalCreditAmount, 2) ?></b></font></td>
                                    </tr>
                                </table>
                                <hr width="800" size="1" color="#CCCCCC">

                                <?php
                                $content_totals = ob_get_contents();
                                ob_end_clean();
                                echo($content_totals);


                                ob_start();
                                ?>


                                <center>
                                    <b><font face="arial" size="4">Rubicon Savings Summary Below</font></b><br>
                                    <br>

                                    <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                        <tr>
                                            <td width="266" bgcolor="#CCCCCC" valign="top">
                                        <center>
                                            <font face="arial" size="2"><b>This Month's Hauler Savings</b></font>
                                        </center>
                                        </td>

                                        <td width="266" bgcolor="#CCCCCC" valign="top">
                                        <center>
                                            <font face="arial" size="2"><b>Year To Date Hauler Saving</b></font>
                                        </center>
                                        </td>

                                        <td width="266" bgcolor="#CCCCCC" valign="top">
                                        <center>
                                            <font face="arial" size="2"><b>Rubicon Total Hauler Savings</b></font>
                                        </center>
                                        </td>
                                        </tr>
                                    </table>
                                    <table width="800" cellpadding="2" cellspacing="1" style="border: 1px solid #cccccc;">
                                        <tr>
                                            <td width="266" bgcolor="#F0F0F0" valign="top">
                                        <center>
                                            <font face="arial" size="2"><b>$<?php echo number_format($runningBenchmark - $hauler_pricing, 2) ?></b></font>
                                        </center>
                                        </td>
                                        <?php
                                        // List of all accounts to check for savings stats
                                        $subAccounts[] = $account_id; // Add current account id
                                        $accStr = implode(',', $subAccounts);

                                        // Lookup ytd savings and all time savings
                                        $q = "SELECT SUM(invoice_benchmark) as total_benchmark,SUM(invoice_hauler_cost) as total_hauler_cost,SUM(invoice_newprice) as total_newprice FROM invoice WHERE account_id IN ($accStr) AND invoice_deleted='no'";
                                        $allTime = $db->query(Database::SELECT, $q)->current();

                                        $myinvoicedate = $invoiceData['invoice_dateend'];
                                        $yearstart = date("Y", strtotime($myinvoicedate));
                                        $q = "SELECT SUM(invoice_benchmark) as total_benchmark,SUM(invoice_hauler_cost) as total_hauler_cost,SUM(invoice_newprice) as total_newprice FROM invoice WHERE account_id IN ($accStr) AND invoice_deleted='no'";
                                        $q .= " AND invoice_dateend <= '$myinvoicedate' AND invoice_dateend >= '$yearstart' ";
                                        $ytd = $db->query(Database::SELECT, $q)->current();
                                        ?>
                                        <td width="266" bgcolor="#F0F0F0" valign="top">
                                        <center>
                                            <font face="arial" size="2"><b>$<?php echo number_format($ytd['total_benchmark'] - ($ytd['total_newprice'] - ($ytd['total_benchmark'] - $ytd['total_newprice'])), 2) ?></b></font>
                                        </center>
                                        </td>

                                        <td width="266" bgcolor="#F0F0F0" valign="top">
                                        <center>
                                            <font face="arial" size="2"><b>$<?php echo number_format($allTime['total_benchmark'] - ($allTime['total_newprice'] - ($allTime['total_benchmark'] - $allTime['total_newprice'])), 2) ?></b></font>
                                        </center>
                                        </td>
                                        </tr>
                                    </table><br>
                                    <br>

                                    <?php
                                    $content_savings = ob_get_contents();
                                    ob_end_clean();
                                    echo($content_savings);

                                    if(trim($invoiceData['invoice_comments']) != "" && $showcomments)
                                    {
                                        ?>
                                        <b><font face="arial" size="2">Comments</font></b>
                                        <table cellpadding="0" cellspacing="0" border="1" style="border: 1px solid #CCCCCC;" width="800">
                                            <tr><td align="left">
                                                    <div style="padding: 5px;">
                                                        <?php echo $invoiceData['invoice_comments'] ?>
                                                    </div>
                                                </td></tr>
                                        </table>
                                        <?php
                                    }
                                    ?>

                                    <center>
                                        <b><font face="arial" size="4">Thank You for Your Business!</font></b><br>
                                        <br>
                                        <hr width="800" size="1" color="#CCCCCC">

                                        <center>
                                            <br>

                                            <center>
                                                <font face="arial" size="2">&#169; Copyright 2010 Advanced Hauler Billing System</font>
                                            </center>
                                        </center>
                                        </center>
                                        </center>
                                        </center>

                                        <?php
                                        $content_entire = ob_get_contents();
                                        ob_end_clean();
                                        // Input content_totals, content_savings
                                        $content_entire = str_replace('%%%content_totals%%%', $content_totals, $content_entire);
                                        $content_entire = str_replace('%%%content_savings%%%', $content_savings, $content_entire);
                                        echo($content_entire);
                                        ?>
